package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    /**
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        Set<Object> keys = redisTemplate.keys("dish:*");
        redisTemplate.delete(keys);
        return R.success("");
    }

    /**
     * 分页查询菜品信息（包括菜品分类信息）
     */
    @GetMapping("page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        Page<DishDto> dishDtoPage = dishService.pageDishDto(page, pageSize, name);
        return R.success(dishDtoPage);
    }

    /**
     * 修改:回显菜品详情信息
     */
    @GetMapping("{id}")
    public R<DishDto> findById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlowers(id);
        return R.success(dishDto);
    }

    /**
     * 修改:保存菜品详情信息
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlowers(dishDto);
        return R.success("");
    }

    /**
     * 修改菜品状态启售、停售
     */
    @PostMapping("status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, Long[] ids) {
        dishService.update()
                .set("status", status)
                .in("id", ids).update();
        return R.success("");
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    public R<String> deleteById(Long[] ids) {
        dishService.deleteByIds(ids);
        return R.success("");
    }

    /**
     * 根据分类id查询该分类菜品信息
     */
    @GetMapping("list")
    public R<List<DishDto>> list(Long categoryId, String name) {
        //先查询redis，有就返回，没有就查询数据库
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get("dish:"+(categoryId!=null?categoryId:name));
        if (dishDtoList != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        List<DishDto> list = dishService.listDishDto(categoryId, name);
        redisTemplate.opsForValue().set("dish:"+(categoryId!=null?categoryId:name),list);
        return R.success(list);
    }
}
